package gstruct.sequential;

import java.util.AbstractCollection;
import java.util.Collections;
import java.util.Iterator;

/**
 * Promotes an iterable to a readonly collection, by calculating its size.
 * <p><b>Beware</b> that this class will fail if the base iterable is concurrently modified.</p>
 * The size is dynamically computed each time {@link #size()} gets called,
 * in contrast to {@link StaticallySizedIterable}, which only computes it once.
 * @author Giulio Franco <giulio_franco@msn.com>
 *
 * @param <E> Type of the contained objects
 */
public class DynamicallySizedIterable<E> extends AbstractCollection<E> {
	
	private final Iterable<E> baseIterable;
	
	public DynamicallySizedIterable() {
		baseIterable = Collections.emptyList();
	}
	
	public DynamicallySizedIterable(Iterable<E> base) {
		this.baseIterable = base;
	}
	
	@Override
	public Iterator<E> iterator() {
		return baseIterable.iterator();
	}

	@Override
	public int size() {
		int res = 0;
		for (@SuppressWarnings("unused") E e : baseIterable) {
			res += 1;
		}
		return res;
	}
	
}
